package com.ai.zhly.util.sms.client;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.ai.zhly.util.sms.msg.MsgHead;
import com.ai.zhly.util.sms.msg.Msg_Cmpp_Active_Test;
import com.ai.zhly.util.sms.msg.Msg_Cmpp_Connect;
import com.ai.zhly.util.sms.msg.Msg_Cmpp_Connect_Resp;
import com.ai.zhly.util.sms.msg.Msg_Cmpp_Submit;
import com.ai.zhly.util.sms.msg.Msg_Cmpp_Submit_Resp;
import com.ai.zhly.util.sms.msg.Msg_Command;
import com.ai.zhly.util.sms.utils.MakeMessage;
import com.ai.zhly.util.sms.utils.MsgUtils;

/**
 * 
 * @company：AsiaInfo BDX-DS-PSO NFJD/XZ/GD Dept.-GZ
 * @author：xw.jiang on 2015年11月13日
 * @email:jiangxw@asiainfo.com
 * @description:短信发送连接器
 */
public class SPConnector extends Thread {

	// 写日志文件
	static Logger logger = Logger.getLogger(SPConnector.class.getName());
	// sp端接收到得消息
	private List<MsgHead> msg_recieve = new ArrayList<MsgHead>();

	private java.io.OutputStream ous;
	private java.io.InputStream ins;
	private java.net.Socket sc;

	// 接收到，等处理回复的Deliver队列
	private boolean isRunning = true;// 运行标志

	public SPConnector(Socket sc) {
		this.sc = sc;
		initIo();
	}

	/**
	 * 初始化IO
	 */
	public void initIo() {
		try {
			ous = sc.getOutputStream();
			ins = sc.getInputStream();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * 1：向ISMG发送登录消息
	 * 
	 * @param cmpp_connect
	 * @return
	 * @throws IOException
	 */
	public int connect(Msg_Cmpp_Connect cmpp_connect) throws Exception {
		byte[] connect_data = MsgUtils.packMsg(cmpp_connect);
		this.sendMsg(connect_data);
		// 读取应答:
		byte[] data = recv();
		MsgHead msg = MsgUtils.praseMsg(data);
		// 解包为一个MsgLoginResp对象
		Msg_Cmpp_Connect_Resp mlr = (Msg_Cmpp_Connect_Resp) msg;
		return mlr.getStatus();
	}

	/**
	 * 1将字节流发送出去
	 * 
	 * @param data
	 *            数据
	 * @param output
	 *            发送出去
	 */
	public boolean sendMsg(byte[] data) {
		try {
			ous.write(data);
			ous.flush();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	@SuppressWarnings("static-access")
	@Override
	public void run() {
		while (isRunning) {
			try {
				Thread.currentThread().sleep(1000);
				byte[] msgISMG = recv();
				MsgHead msg = MsgUtils.praseMsg(msgISMG);
				// 同步放入消息接收队列
				synchronized (msg_recieve) {
					msg_recieve.add(msg);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				logger.info("Socket关闭，短信发送连接已断开");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 接收消息时,肯定是要先读消息头,先取四个字节
	// 从输入流上接收消息
	public byte[] recv() throws Exception {
		java.io.DataInputStream dis = new java.io.DataInputStream(ins);
		int len = dis.readInt();
		// cmpp消息最长是不会招过200字节的
		// 1.恶意消息 10 10000
		if ((len > 0) && (len < 500)) {
			byte[] data = new byte[len - 4];
			dis.readFully(data);
			return data;
		} else {
			// 1.输出不处理消息日志
			logger.info("消息内容过长，有可能为恶意消息，系统不接收和处理该消息内容");
			// 2.关闭该连接
			new SPClient().closeSP();
		}
		return null;
	}

	/**
	 * 发送链路检测消息(心跳包) 用以检测
	 * 
	 * @throws Exception
	 */
	public void sendLinkTest() throws Exception {
		Msg_Cmpp_Active_Test msgCmppTest = MakeMessage
				.makeMsg_Cmpp_Active_Test();
		byte[] byteMsgCmppTest = MsgUtils.packMsg(msgCmppTest);
		boolean flag = true;
		int count = 0;
		while (flag) {
			logger.info("发送一条链路测试短信");
			this.sendMsg(byteMsgCmppTest);
			byte[] data = recv();
			if (data == null) {
				count++;
				if (count == 3) {
					flag = false;
					new SPClient().closeSP();
				}
			} else {
				logger.info("收到链路测试短信，对端正常运行");
			}
			Thread.currentThread().sleep(10000);
			count++;
		}
	}

	/**
	 * 系统向指定的用户[电话号码] 发送短信
	 * 
	 * @return
	 */
	public int sendMessage() {
		try {
			Msg_Cmpp_Submit msgCmppSubmit = MakeMessage.makemakeMsg_Submit();
			logger.info("编号为" + msgCmppSubmit.getSequence_Id() + "正在发送...");
			byte[] byteMsgCmppSubmit = MsgUtils.packMsg(msgCmppSubmit);
			this.sendMsg(byteMsgCmppSubmit);
			byte[] data = recv();
			MsgHead msg = MsgUtils.praseMsg(data);
			Msg_Cmpp_Submit_Resp mcs = (Msg_Cmpp_Submit_Resp) msg;
			if (msg != null) {
				if (Msg_Command.CMPP_SUBMIT_RESP == msg.getCommand_Id()) {
					Msg_Cmpp_Submit_Resp mcsr = (Msg_Cmpp_Submit_Resp) msg;
					switch (mcs.getResult()) {
					case 0:
						logger.info("编号为" + mcsr.getSequence_Id() + "的短信发送成功");
						break;
					case 1:
						logger.info(
								"编号为" + mcsr.getSequence_Id() + "的短信消息结构错误");
						break;
					case 2:
						logger.info("编号为" + mcsr.getSequence_Id() + "的短信命令字错误");
						break;
					case 3:
						logger.info(
								"编号为" + mcsr.getSequence_Id() + "的短信消息序号重复");
						break;
					case 4:
						logger.info(
								"编号为" + mcsr.getSequence_Id() + "的短信消息长度错误");
						break;
					case 5:
						logger.info(
								"编号为" + mcsr.getSequence_Id() + "的短信资费代码错误");
						break;
					case 6:
						logger.info(
								"编号为" + mcsr.getSequence_Id() + "的短信超过最大信息长");
						break;
					case 7:
						logger.info(
								"编号为" + mcsr.getSequence_Id() + "的短信业务带代码错误");
						break;
					case 8:
						logger.info(
								"编号为" + mcsr.getSequence_Id() + "的短信流量控制错误");
						break;
					default:
						logger.info("编号为" + msg.getSequence_Id() + "的短信发生未知错误");
						break;
					}
				}
			}
			// this.sendLinkTest();
		} catch (Exception e) {
			logger.info("短信发送异常");
			new SPClient().closeSP();
			return -1;
		}
		return 0;
	}

	/**
	 * 1:该方法为启动一个线程处理 接收到得消息 返回相应的回复消息
	 *//*
		 * public void processRecieveMsg() { java.lang.Runnable runner = new
		 * java.lang.Runnable() {
		 * 
		 * @SuppressWarnings("static-access") public void run() { while
		 * (isRunning) { if (msg_recieve.size() == 0) {
		 * 
		 * } MsgHead msg = msg_recieve.get(0); if(msg != null){
		 * if(Msg_Command.CMPP_SUBMIT_RESP == msg.getCommand_Id()){
		 * Msg_Cmpp_Submit_Resp mcs = (Msg_Cmpp_Submit_Resp)msg; switch
		 * (mcs.getResult()) { case
		 * 0:logger.info("编号为"+msg.getSequence_Id()+"的短信发送成功");break; case
		 * 1:logger.info("编号为"+msg.getSequence_Id()+"的短信消息结构错误");break; case
		 * 2:logger.info("编号为"+msg.getSequence_Id()+"的短信命令字错误");break; case
		 * 3:logger.info("编号为"+msg.getSequence_Id()+"的短信消息序号重复");break; case
		 * 4:logger.info("编号为"+msg.getSequence_Id()+"的短信消息长度错误");break; case
		 * 5:logger.info("编号为"+msg.getSequence_Id()+"的短信资费代码错误");break; case
		 * 6:logger.info("编号为"+msg.getSequence_Id()+"的短信超过最大信息长");break; case
		 * 7:logger.info("编号为"+msg.getSequence_Id()+"的短信业务带代码错误");break; case
		 * 8:logger.info("编号为"+msg.getSequence_Id()+"的短信流量控制错误");break; default:
		 * logger.info("编号为"+msg.getSequence_Id()+"的短信发生未知错误"); break; } } }
		 * msg_recieve.remove(0); } } }; Thread t = new Thread(runner);
		 * t.start(); }
		 */

	/**
	 * 1:关闭时 接收与发送都关闭
	 */
	public void closeConnect() {
		this.isRunning = false;
	}

}
